package com.ctg.behavior.calc.impala.builder.retentions;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.impala.report.retentions.CtRetentionsReport;
import com.ctg.behavior.calc.impala.report.retentions.CtRetentionsUserIdsReport;
import com.ctg.behavior.common.retentions.CtRetentionsCalcBody;
import com.ctg.behavior.common.retentions.CtRetentionsSliceBody;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtRetentionsUserIdsReprotBuilder {

	@Autowired
	private CtRetentionsReportBuilder retentionsReportBuilder;

	public CtRetentionsUserIdsReport doBuilder(CtRetentionsSliceBody retentionsSliceBody) {

		CtRetentionsUserIdsReport userIdsReport = new CtRetentionsUserIdsReport();
		
		userIdsReport.setSliceInterval(retentionsSliceBody.getSliceInterval());
		userIdsReport.setSliceDate(retentionsSliceBody.getSliceDate());
		userIdsReport.setSliceByValues(retentionsSliceBody.getSliceByValues());
		userIdsReport.getSli().setId(retentionsSliceBody.getSli().getId());
		userIdsReport.getSli().setValue(retentionsSliceBody.getSli().getValue());
		
		// 如查是查看整体留存
		if (StringUtils.isEmpty(retentionsSliceBody.getSliceDate())) {
			BeanUtils.copyProperties(retentionsSliceBody, userIdsReport);
			userIdsReport.setTheFirstEventFromDate(retentionsSliceBody.getFromDate());
			userIdsReport.setTheFirstEventToDate(retentionsSliceBody.getToDate());
			return userIdsReport;
		}

		CtRetentionsCalcBody retentionsCalcBody = (CtRetentionsCalcBody) retentionsSliceBody;
		List<CtRetentionsReport> retentionsReports = retentionsReportBuilder.doBuilder(retentionsCalcBody);
		// 查找对应的RetentionsReport
		for (int index = 0; index < retentionsReports.size(); index++) {
			CtRetentionsReport retentionsReport = retentionsReports.get(index);
			if (retentionsSliceBody.getSliceDate().compareTo(retentionsReport.getWhichDay()) >= 0) {
				if (index + 1 < retentionsReports.size()) {
					CtRetentionsReport nextRetentionsReport = retentionsReports.get(index + 1);
					if (retentionsSliceBody.getSliceDate().compareTo(nextRetentionsReport.getWhichDay()) < 0) {
						BeanUtils.copyProperties(retentionsReport, userIdsReport);
						break;
					}
				} else {
					BeanUtils.copyProperties(retentionsReport, userIdsReport);
					break;
				}
			}
		}
		// 查找对应对Cell
		if (!StringUtils.isEmpty(retentionsSliceBody.getSliceInterval())) {
			userIdsReport.setSliceCalcDate(userIdsReport.getCellDates().get(Integer.valueOf(retentionsSliceBody.getSliceInterval())));
		}
		log.info("userIdsReport={}", JSON.toJSONString(userIdsReport));

		return userIdsReport;
	}

}
